package com.example.app2;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.util.Log;

import androidx.annotation.Nullable;

import com.example.app2.pojo.CartInfo;
import com.example.app2.pojo.GoodsInfo;
import com.example.app2.pojo.User;
import com.example.app2.util.SharedUtil;

import java.sql.SQLData;
import java.sql.SQLInput;
import java.util.ArrayList;
import java.util.List;

public class ShoppingDBHelper extends SQLiteOpenHelper {
    private static String DB_NAME="shopping.db";
    private  static final String TABLE_GOODS_INFO="goods_info";
    private  static final String TABLE_CART_INFO="cart_info";
    private static int DB_VERSION=1;
    private static ShoppingDBHelper mHelper=null;
    private SQLiteDatabase mRDB=null;
    private SQLiteDatabase mWDB=null;
    private ShoppingDBHelper(Context context){
        super(context, DB_NAME, null, DB_VERSION);
    }
    //利用单例模式获取数据库帮助其的唯一实例
    public static ShoppingDBHelper getInstance(Context context)
    {
        if(mHelper==null)
        {
            mHelper=new ShoppingDBHelper(context);
        }
        return  mHelper;
    }
    //打开读连接
    public SQLiteDatabase openReadLink()
    {
        if(mRDB==null||!mRDB.isOpen())
        {
            mRDB=mHelper.getReadableDatabase();
        }
        return mRDB;
    }

    //打开写连接
    public SQLiteDatabase openWriteLink()
    {
        if(mWDB==null||!mWDB.isOpen())
        {
            mWDB=mHelper.getReadableDatabase();
        }
        return mWDB;
    }
    //关闭数据库连接
    public void closeLink()
    {
        if(mRDB!=null&&mRDB.isOpen())
        {
            mRDB.close();
            mRDB=null;
        }
        if(mWDB!=null&&mWDB.isOpen())
        {
            mWDB.close();
            mWDB=null;
        }
    }



    @Override
    public void onCreate(SQLiteDatabase db) {
        String create_goods_sql = "CREATE TABLE IF NOT EXISTS " + TABLE_GOODS_INFO +
                " (_id INTEGER PRIMARY KEY  AUTOINCREMENT NOT NULL," +
                "name VARCHAR NOT NULL," + "description VARCHAR NOT NULL," +
                "price FLOAT NOT NULL," + "pic_path VARCHAR NOT NULL);" ;
        db.execSQL(create_goods_sql);
        String create_cart_sql = "CREATE TABLE IF NOT EXISTS " + TABLE_CART_INFO +
                " (_id INTEGER PRIMARY KEY  AUTOINCREMENT NOT NULL," +
                "goods_id INTEGER NOT NULL," + "count INTEGER NOT NULL);" ;
        db.execSQL(create_cart_sql);
        //初始化商品信息
    }



    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
    public void insertGoodsInfo(List<GoodsInfo>infos)
    {
        try {
            //插入多条记录到数据库中
            mWDB.beginTransaction();
            for (GoodsInfo info : infos) {
                ContentValues values=new ContentValues();
                values.put("name",info.name);
                values.put("description",info.description);
                values.put("price",info.price);
                values.put("pic_path",info.picPath);
                mWDB.insert(TABLE_GOODS_INFO,null,values);
            }
            mWDB.setTransactionSuccessful();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            mWDB.endTransaction();
        }

    }
    //查询所有商品信息
    public List<GoodsInfo> queryAllGoodsInfo()
    {
        String sql="select * from "+TABLE_GOODS_INFO;
        List<GoodsInfo> list=new ArrayList<>();
        Cursor cursor = mRDB.rawQuery(sql,null);
        while(cursor.moveToNext())
        {
            GoodsInfo info = new GoodsInfo();
            info.id=cursor.getInt(0);
            info.name=cursor.getString(1);
            info.description=cursor.getString(2);
            info.price=cursor.getFloat(3);
            info.picPath=cursor.getString(4);
            list.add(info);
        }

        cursor.close();
        return  list;
    }

    public void insertCartInfo(int goodsId) {
        //首先需要查询出该商品在购物车中是否有了
        CartInfo info = queryCartInfoByGoodsId(goodsId);
        //如果没有，则插入，如果有，则修改数量加1
        ContentValues values=new ContentValues();
        values.put("goods_id",goodsId);
        if(info==null)
        {
            values.put("count",1);
            long ret = mWDB.insert(TABLE_CART_INFO, null, values);
        }
        else
        {
            values.put("_id",info.id);
            values.put("count",info.count+1);
            int ret = mWDB.update(TABLE_CART_INFO, values, "_id=?", new String[]{String.valueOf(info.id)});
        }

    }
    public CartInfo queryCartInfoByGoodsId(int goodsId)
    {
        String sql="select * from "+TABLE_CART_INFO+" where goods_id=:goodsId";
        Cursor cursor = mRDB.rawQuery(sql, new String[]{String.valueOf(goodsId)});
        CartInfo info=null;
        if(cursor.moveToNext())
        {
            info=new CartInfo();
            info.goodsId=goodsId;
            info.id=cursor.getInt(0);
            info.count=cursor.getInt(2);
            return info;
        }
        return null;
    }

    public int countCartInfo() {
        String sql="select sum(count) from "+TABLE_CART_INFO;
        Cursor cursor = mRDB.rawQuery(sql, null);
        int count=0;
        if(cursor.moveToNext())
        {
            count = cursor.getInt(0);
        }

        return count;
    }
    //查询购物车中所有的信息列表
    public List<CartInfo> queryAllCartInfo()
    {
        List<CartInfo>  list=new ArrayList<>();
        Cursor cursor = mRDB.query(TABLE_CART_INFO, null, null, null, null, null, null, null);
        while(cursor.moveToNext())
        {
            CartInfo info=new CartInfo();
            info.id=cursor.getInt(0);
            info.goodsId=cursor.getInt(1);
            info.count=cursor.getInt(2);
            list.add(info);
        }
        return list;


    }

    public GoodsInfo queryGoodsInfoById(int goodsId) {
        GoodsInfo info=null;
        Cursor cursor = mRDB.query(TABLE_GOODS_INFO, null, "_id=?", new String[]{String.valueOf(goodsId)}, null, null, null, null);
        if(cursor.moveToNext())
        {
            info=new GoodsInfo();
            info.id=cursor.getInt(0);
            info.name=cursor.getString(1);
            info.description=cursor.getString(2);
            info.price=cursor.getFloat(3);
            info.picPath=cursor.getString(4);
        }
        return info;

    }

    public void deleteCartInfoById(int goodsId)
    {
        mWDB.delete(TABLE_CART_INFO,"goods_id=?",new String[]{String.valueOf(goodsId)});
    }
    public void deleteAllCartInfo()
    {
        mWDB.delete(TABLE_CART_INFO,"1=1",null);
    }
}
